package io.gitee.zhangbinhub.acp.boot.socket

import io.gitee.zhangbinhub.acp.boot.conf.AcpUdpServerConfiguration
import io.gitee.zhangbinhub.acp.boot.daemon.DaemonServiceManager
import io.gitee.zhangbinhub.acp.boot.init.BaseInitSocketServer
import io.gitee.zhangbinhub.acp.boot.log.LogAdapter
import io.gitee.zhangbinhub.acp.boot.socket.base.UdpServerHandle
import io.gitee.zhangbinhub.acp.boot.socket.udp.UdpServer

/**
 * 初始化UDP服务
 */
class InitUdpServer(
    private val logAdapter: LogAdapter,
    private val acpUdpServerConfiguration: AcpUdpServerConfiguration,
    private val udpServerHandle: MutableMap<String, UdpServerHandle>
) : BaseInitSocketServer() {

    fun startUdpServer() {
        logAdapter.info("start udp listen service ...")
        if (udpServerHandle.isNotEmpty()) {
            udpServerHandle.forEach { entity -> addServerHandle(entity.key, entity.value) }
        }
        try {
            val listens = acpUdpServerConfiguration.listeners
            if (listens.isNotEmpty()) {
                listens.forEach { listen ->
                    run {
                        if (listen.enabled) {
                            val beanName = listen.handleBean
                            getSocketServerHandle(beanName)?.let { handle ->
                                val port = listen.port
                                val server = UdpServer(logAdapter, port, listen, handle)
                                val sub = Thread(server)
                                sub.isDaemon = true
                                sub.start()
                                DaemonServiceManager.addService(server)
                                logAdapter.info("start udp listen service Success [" + listen.name + "] , port:" + listen.port)
                            } ?: logAdapter.error("udp handle bean [$beanName] is invalid!")
                        } else {
                            logAdapter.info("udp listen service is disabled [" + listen.name + "]")
                        }
                    }
                }
            } else {
                logAdapter.info("No udp listen service was found")
            }
        } catch (e: Exception) {
            logAdapter.error(e.message, e)
        } finally {
            logAdapter.info("start udp listen service finished!")
        }
    }

}
